{% extends "base.html" %}

{% block title %}电子围栏报警管理 - 告警系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="fw-bold text-primary">电子围栏报警管理</h1>
    <div>
        <button class="btn btn-outline-secondary me-2" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise"></i> 刷新
        </button>
        <div class="btn-group">
            <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                每页 {{ page_size }} 条
            </button>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="?page=1&page_size=5{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}{% if device_id %}&device_id={{ device_id }}{% endif %}">5条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=10{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}{% if device_id %}&device_id={{ device_id }}{% endif %}">10条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=20{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}{% if device_id %}&device_id={{ device_id }}{% endif %}">20条/页</a></li>
                <li><a class="dropdown-item" href="?page=1&page_size=50{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}{% if device_id %}&device_id={{ device_id }}{% endif %}">50条/页</a></li>
            </ul>
        </div>
    </div>
</div>

<!-- 搜索和筛选区域 -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="get">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">设备ID</label>
                    <select name="device_id" class="form-select">
                        <option value="">全部设备</option>
                        {% for device in device_list %}
                        <option value="{{ device }}" {% if device_id == device %}selected{% endif %}>{{ device }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <div class="col-md-3">
                    <label class="form-label">开始日期</label>
                    <input type="date" name="start_date" class="form-control" value="{{ start_date }}">
                </div>
                
                <div class="col-md-3">
                    <label class="form-label">结束日期</label>
                    <input type="date" name="end_date" class="form-control" value="{{ end_date }}">
                </div>
                
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-filter"></i> 筛选
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

{% if alarms and alarms|length > 0 %}
<div class="card shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="bg-primary text-white">
                <tr>
                    <th width="40" class="text-center">
                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                    </th>
                    <th>序号</th>
                    <th>设备ID</th>
                    <th>电子围栏位置</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>持续时间</th>
                    <th>报警状态</th>
                </tr>
            </thead>
            <tbody>
                {% for alarm in alarms %}
                <tr>
                    <td class="text-center">
                        <input type="checkbox" class="alert-checkbox" value="{{ alarm.EFAlarmID }}" onchange="updateDeleteButtonState()">
                    </td>
                    <td class="fw-medium">{{ (page - 1) * page_size + loop.index }}</td>
                    <td>{{ alarm.FenceName }}</td>
                    <td>{{ alarm.FenceLocation or '未知位置' }}</td>
                    <td>{{ alarm.StartTime.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                    <td>
                        {% if alarm.EndTime %}
                            {{ alarm.EndTime.strftime('%Y-%m-%d %H:%M:%S') }}
                        {% else %}
                            <span class="text-muted">-</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if alarm.duration %}
                            {{ alarm.duration | format_duration }}
                        {% else %}
                            <span class="text-muted">-</span>
                        {% endif %}
                    </td>
                    <td>
                        <span class="badge {% if alarm.FenceState == '报警中' %}bg-danger{% else %}bg-success{% endif %}">
                            {{ alarm.FenceState }}
                        </span>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<!-- 分页控件 -->
<div class="mt-4">
    <nav aria-label="分页导航">
        <ul class="pagination justify-content-center">
            <li class="page-item {% if page == 1 %}disabled{% endif %}">
                <a class="page-link" href="?page={{ page - 1 }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">
                    <i class="bi bi-chevron-left"></i> 上一页
                </a>
            </li>
            
            {% if total_pages <= 7 %}
                {% for p in range(1, total_pages + 1) %}
                    <li class="page-item {% if p == page %}active{% endif %}">
                        <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ p }}</a>
                    </li>
                {% endfor %}
            {% else %}
                {% if page <= 4 %}
                    {% for p in range(1, 6) %}
                        <li class="page-item {% if p == page %}active{% endif %}">
                            <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ p }}</a>
                        </li>
                    {% endfor %}
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    <li class="page-item"><a class="page-link" href="?page={{ total_pages - 1 }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ total_pages - 1 }}</a></li>
                    <li class="page-item"><a class="page-link" href="?page={{ total_pages }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ total_pages }}</a></li>
                {% elif page >= total_pages - 3 %}
                    <li class="page-item"><a class="page-link" href="?page=1&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">1</a></li>
                    <li class="page-item"><a class="page-link" href="?page=2&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">2</a></li>
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    {% for p in range(total_pages - 4, total_pages + 1) %}
                        <li class="page-item {% if p == page %}active{% endif %}">
                            <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ p }}</a>
                        </li>
                    {% endfor %}
                {% else %}
                    <li class="page-item"><a class="page-link" href="?page=1&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">1</a></li>
                    <li class="page-item"><a class="page-link" href="?page=2&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">2</a></li>
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    {% for p in range(page - 2, page + 3) %}
                        <li class="page-item {% if p == page %}active{% endif %}">
                            <a class="page-link" href="?page={{ p }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ p }}</a>
                        </li>
                    {% endfor %}
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    <li class="page-item"><a class="page-link" href="?page={{ total_pages - 1 }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ total_pages - 1 }}</a></li>
                    <li class="page-item"><a class="page-link" href="?page={{ total_pages }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">{{ total_pages }}</a></li>
                {% endif %}
            {% endif %}
            
            <li class="page-item {% if page == total_pages %}disabled{% endif %}">
                <a class="page-link" href="?page={{ page + 1 }}&page_size={{ page_size }}&device_id={{ device_id }}&start_date={{ start_date }}&end_date={{ end_date }}">
                    下一页 <i class="bi bi-chevron-right"></i>
                </a>
            </li>
        </ul>
    </nav>
    <div class="text-center text-muted mt-2">
        显示 {{ (page - 1) * page_size + 1 }} 到 {{ (page - 1) * page_size + alarms|length }} 条，共 {{ total }} 条记录
    </div>
</div>
{% else %}
<div class="d-flex justify-content-center align-items-center" style="min-height: 400px;">
    <div class="alert alert-primary text-center p-5 rounded-3">
        <div class="mb-3">
            <i class="bi bi-info-circle fs-1 text-primary"></i>
        </div>
        <h4 class="fw-bold">
            {% if start_date or end_date or device_id %}
                未找到匹配的电子围栏报警
            {% else %}
                暂无电子围栏报警数据
            {% endif %}
        </h4>
        <p class="mt-2 text-muted">
            {% if start_date or end_date %}
                没有找到指定时间范围内的电子围栏报警
            {% elif device_id %}
                没有找到设备 "{{ device_id }}" 的电子围栏报警
            {% else %}
                系统中没有记录的电子围栏报警
            {% endif %}
        </p>
        {% if start_date or end_date or device_id %}
            <a href="?page=1&page_size={{ page_size }}" class="btn btn-outline-primary mt-3">
                查看所有报警
            </a>
        {% endif %}
    </div>
</div>
{% endif %}

<!-- 批量删除按钮 -->
<div class="d-flex justify-content-end mt-3">
    <button id="deleteSelectedBtn" class="btn btn-danger" disabled onclick="deleteSelectedAlerts()">
        <i class="bi bi-trash"></i> 删除选中项
    </button>
</div>

{% endblock %}

{% block extra_js %}
<script>
    // 全选/取消全选功能
    function toggleSelectAll(checkbox) {
        const checkboxes = document.querySelectorAll('.alert-checkbox');
        checkboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        updateDeleteButtonState();
    }
    
    // 更新删除按钮状态
    function updateDeleteButtonState() {
        const selectedCount = document.querySelectorAll('.alert-checkbox:checked').length;
        const deleteBtn = document.getElementById('deleteSelectedBtn');
        deleteBtn.disabled = selectedCount === 0;
        deleteBtn.innerHTML = `<i class="bi bi-trash"></i> 删除选中项 (${selectedCount})`;
    }
    
    // 删除选中的报警
    function deleteSelectedAlerts() {
        const selectedCheckboxes = document.querySelectorAll('.alert-checkbox:checked');
        if (selectedCheckboxes.length === 0) {
            alert('请先选择要删除的报警');
            return;
        }
        
        if (!confirm(`确定要删除选中的 ${selectedCheckboxes.length} 条报警记录吗？`)) {
            return;
        }
        
        const alarmIds = Array.from(selectedCheckboxes).map(cb => parseInt(cb.value));
        
        fetch('/efence/alerts/delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(alarmIds)
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert(data.message);
                location.reload();
            } else {
                alert('删除失败: ' + (data.message || '未知错误'));
            }
        })
        .catch(error => {
            console.error('删除操作出错:', error);
            alert('删除操作出错: ' + error.message);
        });
    }
</script>
{% endblock %}